/**
 * @file      : main.c
 * @brief     : 程序入口源文件
 * @author    : huenrong (huenrong1028@gmail.com)
 * @date      : 2021-04-10 15:30:09
 *
 * @copyright : Copyright (c) 2021  胡恩荣
 *
 */

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "./queue/queue.h"

// 测试队列
struct queue g_test_queue = {0};

/**
 * @brief  消费者线程
 */
void *consumer_thread(void);

int main(int argc, char *argv[])
{
    int ret = -1;
    // 消费者线程ID
    pthread_t consumer_thread_id;
    uint8_t test_data[256] = {0x11, 0x22, 0x33};

    // 队列初始化
    init_queue(&g_test_queue, 20);

    // 创建消费者线程
    ret = pthread_create(&consumer_thread_id, NULL,
                         (void *)consumer_thread, NULL);
    // 线程创建成功
    if (0 == ret)
    {
        // 线程分离, 结束时自动回收资源
        pthread_detach(consumer_thread_id);
    }

    // 生产者
    while (1)
    {
        ret = insert_queue(&g_test_queue, test_data, 3);
        if (ret > 0)
        {
            printf("insert data to queue: ");
            for (uint8_t i = 0; i < strlen((char *)test_data); i++)
            {
                printf("0x%02X ", test_data[i]);
            }
            printf("\n");
        }

        sleep(1);
    }

    return 0;
}

/**
 * @brief  消费者线程
 */
void *consumer_thread(void)
{
    int ret = -1;
    uint8_t get_data[256] = {0};

    while (1)
    {
        ret = get_queue_with_timeout(&g_test_queue, get_data,
                                     get_queue_length(g_test_queue), 100);
        if (ret > 0)
        {
            printf("get data from queue: ");
            for (uint8_t i = 0; i < strlen((char *)get_data); i++)
            {
                printf("0x%02X ", get_data[i]);
            }
            printf("\n");
        }
    }
}
